<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <!-- <a-row>
          <a-col :span="24">
            <a-form-model-item label="工程量包名" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="packageName">
              <a-input v-model="model.packageName" placeholder="请输入工程量包名"></a-input>
            </a-form-model-item>
          </a-col>
        </a-row> -->
        <a-row>
          <a-col :span="24">
            <a-button class="editable-add-btn" @click="handleAdd"> 新增工程量 </a-button>
            <a-table bordered :data-source="dataSource" :columns="columns">
              <template slot="packageGridId" slot-scope="text, record">
                <div>
                  <a-select v-if="record.editable1" placeholder="请选择" v-model="record.packageGridId"
                    @change="(e) => handleChange1(e, record.key, 'packageGridId')">
                    <a-select-option v-for="mode in packageGridIdList" :key="mode.id" :value="mode.id">
                      {{ mode.gridName }}
                    </a-select-option>
                  </a-select>
                  <template v-else>
                    {{ formatName(text, 'packageGridId') }}
                  </template>
                </div>
              </template>
              <!-- <template slot="packageInfoId" slot-scope="text, record">
                <div>
                  <div v-if="record.editable1">
                    <a-select placeholder="请选择" @change="(e) => handleChange1(e, record.key, 'packageInfoId')">
                      <a-select-option v-for="mode in PackageInfoList" :key="mode.id" :value="mode.id">
                        {{ mode.packageName }}
                      </a-select-option>
                    </a-select>
                  </div>

                  <template v-else>
                    {{ formatName(text, 'packageInfoId') }}
                  </template>
                </div>
              </template> -->
              <template slot="orderd" slot-scope="text, record">
                <div>
                  <template>
                    {{ text }}
                  </template>
                  <!-- <a-input
                    style="margin: -5px 0"
                    :value="record.key"
                    @change="(e) => handleChange1(e.target.value, record.key, 'orderd')"
                  /> -->
                  <!-- <a-input
                    v-if="record.editable1"
                    style="margin: -5px 0"
                    :value="text"
                    @change="(e) => handleChange1(e.target.value, record.key, 'orderd')"
                  />
                  <template v-else>
                    {{ text }}
                  </template> -->
                </div>
              </template>
              <template slot="operation" slot-scope="text, record">
                <a-popconfirm style="margin-right: 5px" v-if="dataSource.length" title="确定删除该数据?"
                  overlayClassName="poperLayTable" @confirm="() => onDelete(record)">
                  <a href="javascript:;">删除</a>
                </a-popconfirm>
                <span v-if="record.editable1">
                  <a @click="() => save(record.key)" style="margin-right: 5px">保存</a>
                  <a-popconfirm title="确定取消吗?" @confirm="() => cancel(record.key)" style="margin-right: 5px">
                    <a>取消</a>
                  </a-popconfirm>
                </span>
                <span v-else style="margin-right: 5px">
                  <a :disabled="editingKey !== ''" @click="() => editK(record)">编辑</a>
                </span>
                <div class="editable-row-operations"></div>
              </template>
            </a-table>
          </a-col>
        </a-row>
      </a-form-model>
    </j-form-container>
  </a-spin>
</template>

<script>
import { httpAction, getAction } from '@/api/manage'
import { validateDuplicateValue } from '@/utils/util'
const EditableCell = {
  template: `
      <div class="editable-cell">
        <div v-if="editable" class="editable-cell-input-wrapper">
          <a-input :value="value" @change="handleChange" @pressEnter="check" /><a-icon
            type="check"
            class="editable-cell-icon-check"
            @click="check"
          />
        </div>
        <div v-else class="editable-cell-text-wrapper">
          {{ value || ' ' }}
          <a-icon type="edit" class="editable-cell-icon" @click="edit" />
        </div>
      </div>
    `,
  props: {
    text: String,
  },

  data() {
    return {
      value: this.text,
      editable: false,
    }
  },
  methods: {
    handleChange(e) {
      const value = e.target.value
      this.value = value
    },
    check() {
      this.editable = false
      this.$emit('change', this.value)
    },
    edit() {
      this.editable = true
    },
  },
}
// const data = []
// for (let i = 0; i < 100; i++) {
//   data.push({
//     key: i.toString(),
//     name: `Edrward ${i}`,
//     packageInfoId: 32,
//     orderd: `London Park no. ${i}`,
//   })
// }
export default {
  name: 'NmcPackageInfoForm',
  props: {
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false,
    },
  },
  components: {
    EditableCell,
  },
  data() {
    return {
      model: {
        dataSource: [
          {
            key: '0',
            packageGridId: '',
            packageInfoId: this.packageInfoId,
            orderd: '1',
            editable1: true,
          },
        ],
      },
      packageInfoId: '',
      editingKey: '',
      cacheData: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {},
      url: {
        add: '/grid/nmcPackageInfo/add',
        addP: '/grid/nmcRelationPackageGrid/add',
        deleteP: '/grid/nmcRelationPackageGrid/delete',
        query: '/grid/nmcRelationPackageGrid/list',
        editP: '/grid/nmcRelationPackageGrid/edit',
        edit: '/grid/nmcRelationPackageGrid/edit',
        queryById: '/grid/nmcPackageInfo/queryById',
        PackageGridlist: '/grid/nmcPackageGrid/list',
        PackageInfoList: '/grid/nmcPackageInfo/list',
      },
      dataSource: [
        {
          key: '0',
          packageGridId: '',
          packageInfoId: this.packageInfoId,
          orderd: '1',
          editable1: true,
        },
      ],
      count: 0,
      packageGridIdList: [],
      ipagination: [
        {
          isorter: {
            order: 'asc',
            column: 'orderd',
          },
        },
      ],

      columns: [
        {
          title: '工程量',
          dataIndex: 'packageGridId',
          width: '25%',
          scopedSlots: { customRender: 'packageGridId' },
        },
        // {
        //   title: '工程量包',
        //   dataIndex: 'packageInfoId',
        //   width: '15%',
        //   scopedSlots: { customRender: 'packageInfoId' },
        // },
        {
          title: '组包排序',
          dataIndex: 'orderd',
          width: '40%',
          scopedSlots: { customRender: 'orderd' },
        },
        {
          title: '操作',
          dataIndex: 'operation',
          width: 180,
          scopedSlots: { customRender: 'operation' },
        },
      ],
      PackageInfoList: [],
    }
  },
  computed: {
    formDisabled() {
      return this.disabled
    },
  },
  created() {
    this.cacheData = [...this.dataSource]
    //备份model原始值
    this.modelDefault = JSON.parse(JSON.stringify(this.model))
  },
  methods: {
    getList() {
      getAction(this.url.PackageGridlist).then((res) => {
        console.log(res)
        this.packageGridIdList = res.result.records
      })
      getAction(this.url.PackageInfoList).then((res) => {
        console.log(res)
        this.PackageInfoList = res.result.records
      })
    },
    editK(record) {
      let key = record.key
      const newData = [...this.dataSource]
      const target = newData.find((item) => key == item.key)
      this.editingKey = key
      if (target) {
        target.editable1 = true
        this.dataSource = newData
      }
    },
    save(key) {
      this.cacheData = [...this.dataSource]
      const newData = [...this.dataSource]
      const newCacheData = [...this.cacheData]
      const target = newData.find((item) => key == item.key)
      const targetCache = newCacheData.find((item) => key == item.key)
      if (target && targetCache) {
        target.packageInfoId = this.packageInfoId
        delete target.editable1
        this.dataSource = newData
        Object.assign(targetCache, target)
        this.cacheData = newCacheData
      }
      this.editingKey = ''
    },
    cancel(key) {
      const newData = [...this.dataSource]
      const target = newData.find((item) => key == item.key)
      this.editingKey = ''
      if (target) {
        Object.assign(
          target,
          this.cacheData.find((item) => key == item.key)
        )
        delete target.editable1
        this.dataSource = newData
      }
    },
    handleChange1(value, key, column) {
      console.log(value, key, column)
      const newData = [...this.dataSource]
      const target = newData.find((item) => key == item.key)
      if (target) {
        target[column] = value
        this.dataSource = newData
      }
    },
    onCellChange(key, dataIndex, value) {
      const dataSource = [...this.dataSource]
      const target = dataSource.find((item) => item.key == key)
      if (target) {
        target[dataIndex] = value
        this.dataSource = dataSource
      }
    },
    onDelete(record) {
      let key = record.key
      if (record.id) {
        httpAction(`${this.url.deleteP}?id=${record.id}`, {}, 'delete').then((res) => {
          this.$message.success(res.message)
        })
      }
      const dataSource = [...this.dataSource]
      this.dataSource = dataSource.filter((item) => item.key != key)
    },
    handleAdd() {
      const { count, dataSource } = this
      const newData = {
        key: count,
        packageGridId: '',
        packageInfoId: this.packageInfoId,
        orderd: dataSource.length + 1,
        editable1: true,
      }
      console.log(count)
      this.dataSource = [...dataSource, newData]
      this.count = count + 1

      this.cacheData = [...this.dataSource]
    },
    formatName(text, type) {
      if (type == 'packageGridId') {
        let texts = this.packageGridIdList.find((i) => i.id == text)
        if (texts) {
          return texts.gridName
        } else {
          return text
        }
      }
    },
    add() {
      this.edit(this.modelDefault)
    },
    edit(record) {
      this.dataSource = []
      this.model = Object.assign({}, record)
      getAction(`${this.url.query}?packageInfoId=${record.id}`, { order: 'asc', column: 'orderd' }).then((res) => {
        if (res.result.records.length != 0) {
          res.result.records.forEach((i, index) => {
            i.key = index
            this.dataSource.push(i)
          })
        } else {
          this.dataSource = [...this.model.dataSource]
        }
        this.count = this.dataSource.length
      })
      this.packageInfoId = record.id
      this.getList()
      this.visible = true
    },
    submitForm() {
      const that = this
      // 触发表单验证
      this.$refs.form.validate((valid) => {
        if (valid) {
          that.confirmLoading = true
          let httpurl = ''
          let method = ''
          this.model.dataSource = [...this.dataSource]
          console.log(this.model, '.dataSource')
          // if (this.model.id) {
          //   httpurl += this.url.addP
          //   method = 'post'
          // } else {
          //   httpurl += this.url.editP
          //   method = 'put'
          // }
          // console.log(this.cacheData)
          httpAction(this.url.addP, this.dataSource, 'post')
            .then((res) => {
              if (res.success) {
                that.$message.success(res.message)
                that.$emit('ok')
              } else {
                that.$message.warning(res.message)
              }
            })
            .finally(() => {
              that.confirmLoading = false
            })
          return
          this.model.dataSource.forEach((item) => {
            console.log(item)
            let httpurl = ''
            if (!item.id) {
              httpurl += that.url.addP
              method = 'post'
            } else {
              httpurl += that.url.editP
              method = 'put'
            }
            delete item.key
            httpAction(httpurl, item.id ? item : [item], method)
              .then((res) => {
                if (res.success) {
                  that.$message.success(res.message)
                  that.$emit('ok')
                } else {
                  that.$message.warning(res.message)
                }
              })
              .finally(() => {
                that.confirmLoading = false
              })
          })
        }
      })
    },
  },
}
</script>
<style scoped>
.editable-row-operations a {
  margin-right: 8px;
}
</style>
